#include <iostream>
#include "opengauss/libpq-fe.h"
#include "xlnt/xlnt.hpp"
#include <vector>
#include <string>

// 从数据库获取数据并存储到vector中
void fetchDataFromDatabase(const std::string& connInfo, const std::string& query, std::vector<std::vector<std::string>>& data) {
    PGconn* conn = PQconnectdb(connInfo.c_str());
    if (PQstatus(conn) != CONNECTION_OK) {
        std::cerr << "Connection to database failed: " << PQerrorMessage(conn) << std::endl;
        PQfinish(conn);
        return;
    }

    PGresult* res = PQexec(conn, query.c_str());
    if (PQresultStatus(res) != PGRES_TUPLES_OK) {
        std::cerr << "Query execution failed: " << PQerrorMessage(conn) << std::endl;
        PQclear(res);
        PQfinish(conn);
        return;
    }

    int numRows = PQntuples(res);
    int numCols = PQnfields(res);

    for (int row = 0; row < numRows; ++row) {
        std::vector<std::string> rowData;
        for (int col = 0; col < numCols; ++col) {
            rowData.push_back(PQgetvalue(res, row, col));
        }
        data.push_back(rowData);
    }

    PQclear(res);
    PQfinish(conn);
}

int main() {
    // PostgreSQL连接信息
    std::string connInfo = "dbname=postgres port=7654 host='127.0.0.1' application_name=test connect_timeout=5 sslmode=allow user='opsadmin' password='Huawei@123'";
    // 获取表结构的查询语句
    std::string getColumnsQuery = "SELECT * FROM su LIMIT 0";
    // 获取数据的查询语句
    std::string getDataQuery = "SELECT * FROM su";

    std::vector<std::vector<std::string>> columnData;
    fetchDataFromDatabase(connInfo, getColumnsQuery, columnData);

    std::vector<std::string> headers;
    int numCols = PQnfields(PQexec(PQconnectdb(connInfo.c_str()), getColumnsQuery.c_str()));
    for (int i = 0; i < numCols; ++i) {
        headers.push_back(PQfname(PQexec(PQconnectdb(connInfo.c_str()), getColumnsQuery.c_str()), i));
    }

    std::vector<std::vector<std::string>> tableData;
    fetchDataFromDatabase(connInfo, getDataQuery, tableData);

    // 创建Excel工作簿
    xlnt::workbook wb;
    xlnt::worksheet ws = wb.active_sheet();

    // 将表头写入Excel
    for (size_t i = 0; i < headers.size(); ++i) {
        ws.cell(xlnt::cell_reference(i + 1, 1)).value(headers[i]);
    }

    // 将数据写入Excel
    for (size_t i = 0; i < tableData.size(); ++i) {
        for (size_t j = 0; j < tableData[i].size(); ++j) {
            ws.cell(xlnt::cell_reference(j + 1, i + 2)).value(tableData[i][j]);
        }
    }

    // 保存Excel文件
    wb.save("output.xlsx");

    std::cout << "Data exported to Excel successfully" << std::endl;

    return 0;
}